//
//  UIViewController_extentsion.m
//  BDD_TWO
//
//  Created by WangZhenyu on 2018/11/21.
//  Copyright © 2018 WangZhenyu. All rights reserved.
//
#import "UIViewController_extentsion.h"

#define FLOATBAR_HEIGHT 70
#define TAG_FLOATBAR 6000
#define TAG_FLOATBAR_CONTAINER 6001
#define TIMEINTERVAL 3

@implementation UIViewController(custom)

//添加返回按钮
- (void)addBackBtn{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 0, 44, 44);
    [btn setImage:[UIImage systemImageNamed:@"arrow.backward"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(goBackAction) forControlEvents:UIControlEventTouchUpInside];
    [btn setTintColor:TextColor];
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -15;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer,btn_left,  nil];
    
//    UIImage *backButtonBackgroundImage = [UIImage systemImageNamed:@"arrow.backward"];
//        // The background should be pinned to the left and not stretch.
//        backButtonBackgroundImage = [backButtonBackgroundImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backButtonBackgroundImage.size.width - 1, 0, 0)];
//
//        id appearance = [UIBarButtonItem appearanceWhenContainedIn:[CustomBackButtonNavController class], nil];
//        [appearance setBackButtonBackgroundImage:backButtonBackgroundImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage systemImageNamed:@"arrow.backward"] style:UIBarButtonItemStylePlain target:nil action:nil];
//    backItem.title = @"测试";
//    //自定义返回按钮的视图，如细化返回图标。
//    [self.navigationController.navigationBar setBackIndicatorImage:[UIImage systemImageNamed:@"arrow.backward"]];
//    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:[UIImage systemImageNamed:@"arrow.backward"]];
//    //设置tintColor 改变自定图片颜色
//    self.navigationController.navigationBar.tintColor = TextColor;
//    //设置自定义的返回按钮
//    self.navigationItem.backBarButtonItem = backItem;
    
}

//添加返回按钮
- (void)addCloseBackBtn{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 0, 44, 44);
    [btn setImage:[UIImage imageNamed:@"back_arrow2"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(goBackAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -15;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer,btn_left,  nil];
}

//添加左边边按钮
- (UIButton *)addLeftBtn:(NSString *)title{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 0, 20 + title.length * 15.0f, 40);
    [btn setTitleColor:TextColor forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [btn setTitle:[NSString stringWithFormat:@"%@", title] forState:UIControlStateNormal];

    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -15;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_left, nil];
    return btn;
}

//添加右边按钮
- (UIButton *)addRigthBtn:(NSString *)title{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 0, 20 + title.length * 15.0f, 44);
    [btn setTitleColor:TextColor forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [btn setTitle:[NSString stringWithFormat:@"%@", title] forState:UIControlStateNormal];

    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -15;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
    return btn;
}

- (UIButton *)addRigthBtn:(NSString *)title withButtonColor:(UIColor *)colorBtn{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 0, 20 + title.length * 15.0f, 44);
    [btn setTitleColor:colorBtn forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [btn setTitle:[NSString stringWithFormat:@"%@", title] forState:UIControlStateNormal];

    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -15;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
    return btn;
}

- (UIButton *)addRigthBtn:(NSString *)title withButtonImage:(UIImage *)image{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:image forState:UIControlStateNormal];
    [btn setTitleColor:TextColor forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [btn setTitle:[NSString stringWithFormat:@" %@", title] forState:UIControlStateNormal];

    CGSize labelSize = [btn sizeThatFits:CGSizeMake(200, MAXFLOAT)];

    btn.frame=CGRectMake(0, 0, 20 + labelSize.width, 44);
    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -15;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
    return btn;
}

//添加右边按钮
- (UIButton *)addRigthBtnImage:(UIImage *)image{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 0, 44, 44);
    [btn setImage:image forState:UIControlStateNormal];
    [btn setTintColor:TextColor];
    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -10;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
    return btn;
}

//添加右边按钮
- (void)addRigthBtnImage:(NSString *)imageName withBadge:(NSInteger)badge complete:(void (^)(UIButton *actionBtn, UILabel *badgeLabel))success{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(0, 0, 44, 44);
    [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [view addSubview:btn];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(22, 0, 18, 18)];
    label.backgroundColor = RGB(234, 98, 98);
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:11.0f];
    label.textAlignment = NSTextAlignmentCenter;
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = label.frame.size.height / 2.0;
    label.adjustsFontSizeToFitWidth = YES;
    label.minimumScaleFactor = 0.5;
    label.hidden = YES;
    [view addSubview:label];

    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:view];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -10;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
    
    success(btn, label);
}

//添加有文字的返回按钮
- (void)addBackBtnTitle:(NSString *)title{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 25 + title.length * 15.0f, 40);
    [btn setImage:[UIImage imageNamed:@"back_arrow"] forState:UIControlStateNormal];
    [btn setTitle:[NSString stringWithFormat:@" %@", title] forState:UIControlStateNormal];
    [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [btn addTarget:self action:@selector(goBackAction) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -5.5;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_left, nil];
}

//添加右边按钮
- (void)addRigthBtnTitle:(NSString *)title withBadge:(NSInteger)badge complete:(void (^)(UIButton *actionBtn, UILabel *badgeLabel))success{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn.frame = CGRectMake(0, 0, 32, 40);
    btn.frame = CGRectMake(0, 0, 48, 40);
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [btn setTitle:[NSString stringWithFormat:@"%@", title] forState:UIControlStateNormal];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 48,  40)];
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.size.width - 14, 13, 14, 14)];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:9.0f];
    label.textAlignment = NSTextAlignmentCenter;
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = label.frame.size.height / 2.0;
    label.adjustsFontSizeToFitWidth = YES;
    label.layer.borderWidth = 1;
    label.layer.borderColor = [UIColor whiteColor].CGColor;
    label.minimumScaleFactor = 0.5;
    label.text = [NSString stringWithFormat:@"%ld", (long)badge];
    label.hidden = YES;
    [view addSubview:label];
    [view addSubview:btn];

    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:view];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -10;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
    
    success(btn, label);
}

- (void)goBackAction{
    NSArray *viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count>1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)popGestureClose:(UIViewController *)VC
{
    if ([VC.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        //这里对添加到右滑视图上的所有手势禁用
        for (UIGestureRecognizer *popGesture in VC.navigationController.interactivePopGestureRecognizer.view.gestureRecognizers) {
            popGesture.enabled = NO;
        }
        //若开启全屏右滑，不能再使用下面方法，请对数组进行处理
        //VC.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)popGestureOpen:(UIViewController *)VC
{
    if ([VC.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    //这里对添加到右滑视图上的所有手势启用
        for (UIGestureRecognizer *popGesture in VC.navigationController.interactivePopGestureRecognizer.view.gestureRecognizers) {
            popGesture.enabled = YES;
        }
        //若开启全屏右滑，不能再使用下面方法，请对数组进行处理
        //VC.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    
}

- (void)hiddenNavbarLine:(BOOL)hiden {
    if (@available(iOS 15.0, *)) {
        [self.navigationController.navigationBar.subviews.firstObject.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:NSClassFromString(@"_UIBarBackgroundShadowContentImageView")] || [obj isKindOfClass:NSClassFromString(@"_UIBarBackgroundShadowView")]) {
                obj.hidden = hiden;
                *stop = YES;
            }
        }];
    } else {
        if (hiden) {
            [self.navigationController.navigationBar setShadowImage:getColorToImage([UIColor whiteColor])];
        } else {
            [self.navigationController.navigationBar setShadowImage:getColorToImage(rgba(213, 213, 213, 1))];
        }
    }
}

- (void)showSaveImageAlert:(UIImage *)image {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *oneBtn = [UIAlertAction actionWithTitle:@"保存图片到手机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
    }];
    [alertController addAction:oneBtn];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (!error) {
        [self showHUDAlert:@"已保存到系统相册"];
    }else{
        [self showHUDAlert:@"保存失败"];
    }
}

@end
